//微信or余额支付
var wxPay = true;
var balancePay = false;
$("#balance_pay").click(function() {
    $('#balance_pay .iconfont').css('display', 'block');
    $('.weixin_pay .iconfont').css('display', 'none');
    wxPay = false;
    balancePay = true;
})
$(".weixin_pay").click(function() {
    $('#balance_pay .iconfont').css('display', 'none');
    $('.weixin_pay .iconfont').css('display', 'block');
    wxPay = true;
    balancePay = false;
})
$("#go_back").click(function() {
    window.location.href = document.referrer;
})

$("#recharge").click(function() {
        window.location.href = "../html/recharge.html";
    })
    //订单数据orderData
    //优惠券信息 couponData id:couponId  money:couponMoney
var orderData = sessionStorage.getItem("orderData");
var orderDataObj = JSON.parse(orderData);
var sdType = orderDataObj.Types;
var couponData = sessionStorage.getItem("couponData");
var couponMoney = orderDataObj.YouId,
    couponId = orderDataObj.YouMoney;
// 获取订单信息改变dom
$("#queue_mes .content").html(orderDataObj.BangName);
$("#queue_add .content").html(orderDataObj.QuHuoAddress);
$("#desc .content").html("排队时间" + orderDataObj.Quhuo_Date + " " + orderDataObj.Desc);
var paoMoney = Number(orderDataObj.orderMoney)
$("#order_money").html(paoMoney + "元");
if (couponData) {
    var couponDataObj = JSON.parse(couponData);
    var totalMoney = parseInt(orderDataObj.orderMoney) - parseInt(couponDataObj.YouMoney);
    totalMoney = (totalMoney < 0 ? totalMoney = 0 : totalMoney);
    // totalMoney=Math.max(0,parseInt(orderDataObj.WuPin_Money)-parseInt(couponDataObj.YouMoney))
    couponMoney = parseInt(couponDataObj.YouMoney);
    couponId = couponDataObj.YouId;
    $("#total_money").html(totalMoney + "元(已优惠￥" + (couponMoney > parseInt(orderDataObj.orderMoney) ? orderDataObj.orderMoney : couponMoney) + ")");
} else {
    $("#total_money").html(orderDataObj.orderMoney + "元(已优惠￥" + orderDataObj.YouMoney + ")");
}
//获取优惠券信息
$.ajax({
    type: "get",
    url: currentUrl + "/interfaceDOC/firstProject/User.ashx",
    data: {
        "action": "Get_YouHuiQuan",
        "UserId": orderDataObj.UserId
    },
    dataType: "json",
    success: function(data) {
        if (data.msgcode == "1") {
           // console.log(data);
           //可用优惠券数量显示   2017.7.17 GJC
           //canUseNum 可用优惠券数量 （服务费大于优惠券满减金额为可用）
            var canUseNum=0;
            for(var i=0;i<data.data.length;i++){
                if(paoMoney>=data.data[i].OverMoney){
                    canUseNum++;
                }
            }
            $("#coupon_num").html(canUseNum + "张可用");
        }
    },
    error: function(data) {
        console.log("优惠券接口失败");
    }
});
//进入优惠券页面
$("#coupon").click(function() {
    window.location.href = "../html/coupon.html";
    sessionStorage.setItem("couponClickOn", "true");
    sessionStorage.setItem("serveMoney", paoMoney);
})
var isPlaceOrder = false; //是否下单 否
$('.form_submit').click(function() {
    var OrderId = "";
    $(".form_submit").attr({ disabled: "disabled" });
    $.ajax({
        type: "post",
        url: currentUrl + "/interfaceDOC/firstProject/User.ashx?action=Insert_OrderPB",
        data: {
            "Near": orderDataObj.Near,
            "Baowenxiang": orderDataObj.Baowenxiang,
            "QuHuoAddress": orderDataObj.QuHuoAddress,
            "Quhuo_Lng": orderDataObj.Quhuo_Lng,
            "Quhuo_Lat": orderDataObj.Quhuo_Lat,
            "Quhuo_Person": orderDataObj.Quhuo_Person,
            "Quhuo_Tel": orderDataObj.Quhuo_Tel,
            "BangMangId": orderDataObj.BangMangId,
            "BangName": orderDataObj.BangName,
            "ZhiPrice": orderDataObj.ZhiPrice,
            "WuPin_Money": "0",
            "Desc": $("#desc .content").html(),
            "YiSui": orderDataObj.YiSui,
            "Quhuo_Date": orderDataObj.Quhuo_Date,
            "YouId": couponId,
            "YouMoney": couponMoney,
            "OrderMonery": totalMoney,
            "CityId": orderDataObj.CityId,
            "UserId": orderDataObj.UserId,
            "UserTel": orderDataObj.UserTel,
            "Types": orderDataObj.Types,
            "ShiChang": orderDataObj.ShiChang,
            "IsTouBao": orderDataObj.IsTouBao,
            "TouMoney": orderDataObj.TouMoney,
            "PeiMoney": orderDataObj.PeiMoney,
        },
        dataType: "json",
        success: function(data) {
            if (data.msgcode == "1") {
                // console.log(data);
                OrderId = data.data.OrderId;
                sessionStorage.setItem("OrderId", OrderId);
                sessionStorage.setItem("OrderType", orderDataObj.Types);
                payOrder();
            } else {
                $.alert("排队地点信息错误");
                return false
            }
        },
        error: function() {
            console.log("下订单接口错误")
            return false
        },
        complete: function() {
            $(".form_submit").removeAttr("disabled");
        }
    });

    function payOrder() {
        if (isPlaceOrder == false && balancePay == true && wxPay == false && OrderId != "") {
            //余额支付
            $.ajax({
                type: "post",
                url: currentUrl + "/interfaceDOC/firstProject/User.ashx?action=Inser_PayOrder",
                data: {
                    "OrderId": OrderId,
                    "YouHuiId": couponId
                },
                dataType: "json",
                success: function(data) {
                    // console.log(data);
                    if (data.msgcode == "1") {
                        $('.mask').css("display", "block");
                        $('.pay_success').css("display", "block");
                        isPlaceOrder = true; //限制重复下单；
                        var countDown = parseInt(3);

                        function timeShow() {
                            countDown--;
                            $(".count_down").html(countDown);
                            if (countDown < 1) {
                                clearInterval(countdown);
                                $(".count_down").html("倒计时结束！！");
                                $('.mask').css("display", "none");
                                $('.pay_success').css("display", "none");
                                window.location.href = "../html/order_wait.html";
                            }
                        };
                        countdown = setInterval(timeShow, 1000);
                    } else {
                        $.alert(data.msg);
                        return false
                    }
                },
                error: function() {
                    $.alert("支付接口请求错误");
                    return false
                },
            });
        } else if (isPlaceOrder == false && balancePay == false && wxPay == true && OrderId != "") {
            //  微信支付
            $.ajax({
                type: 'post',
                url: currentUrl + '/WxSdjs/PayHandler.ashx',
                data: {
                    action: 'queue',
                    orderId: 'x' + OrderId,
                    openId: localStorage.getItem("openId")
                },
                success: function(response) {
                    var result = JSON.parse(response);
                    if (result.IsOk) {
                        var wxJsApiParam = result.Data;
                        WeixinJSBridge.invoke('getBrandWCPayRequest',
                            JSON.parse(wxJsApiParam),
                            function(res) {
                                if (res.err_msg == "get_brand_wcpay_request:ok") {

                                    $('.mask').css("display", "block");
                                    $('.pay_success').css("display", "block");
                                    isPlaceOrder = true; //限制重复下单；
                                    var countDown = parseInt(3);

                                    function timeShow() {
                                        countDown--;
                                        $(".count_down").html(countDown);
                                        if (countDown < 1) {
                                            clearInterval(countdown);
                                            $(".count_down").html("倒计时结束！！");
                                            $('.mask').css("display", "none");
                                            window.location.href = "../html/order_wait.html";
                                        }
                                    };
                                    countdown = setInterval(timeShow, 1000);
                                }
                                // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                //因此微信团队建议，当收到ok返回时，向商户后台询问是否收到交易成功的通知，若收到通知，前端展示交易成功的界面；若此时未收到通知，商户后台主动调用查询订单接口，查询订单的当前状态，并反馈给前端展示相应的界面。
                            });
                    }

                },
                error: function() {
                    $.alert('微信充值失败，请重试！');
                }
            });



        }
    }
})